package com.lotusfall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lotusfall.pojo.User;
import com.lotusfall.pojo.UserContext;
import com.lotusfall.service.UserService;
import com.lotusfall.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public int addUser(User user) {
        // 密码加密
        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        // 事件处理
        user.setCreated(new Date());
        int i = userMapper.addUser(user);
        return i;
    }

    // 查询所有用户（管理员权限）
    @Override
    public List<User> queryAll() {
        return userMapper.queryAll();
    }

    @Override
    public User getCurrentUser() {
        return UserContext.getUser();
    }

    @Override
    public PageInfo<User> queryUserList(Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<User> userList = this.userMapper.queryUserList(page,pageSize);
        PageInfo<User> userPageInfo = new PageInfo<User>(userList);
        return userPageInfo;
    }

    @Override
    public int setUserAvatar(String username, String url) {
        return this.userMapper.setUserAvatarUrl(username,url);
    }

    @Override
    public User getUserById(Long id) {
        return this.userMapper.getUserById(id);
    }


    // 根据用户名查找用户
    @Override
    public User selectUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }
}
